#coding=utf-8
import re
import os
import json
import requests
import urllib.request
import urllib.parse

from ..common.__const__ import LOG_FILE
from ..common.__script_config__ import script_config


class RemoteLogger(object):
    """远程日志发送"""

    def __init__(self):
        self.url = script_config.remote_log_url

    def writeLog(self, msg):
        content = ''
        level = 'debug'
        #步骤多条消息封装
        msg_list = re.split('[\[\]]', msg, 2)
        level = msg_list[1].strip('\n').lower()
        if level == 'warning':
            level = 'warn'
        content = msg_list[2].strip('\n')
        if len(content) > 0:
            try:
                data = dict()
                data['content'] = content
                data['level'] = level
                # 将字典转成json字符串
                data = json.dumps(data)
                data = urllib.parse.quote(data)
                data = data.encode(encoding='utf-8')
                url = self.url
                headers = {'Content-Type': 'application/json'}
                request = urllib.request.Request(url=url, headers=headers)
                response = urllib.request.urlopen(request, data, timeout=5)  # 发送请求
                body = response.read().decode('utf-8')
            except Exception as e:
                logtext = ['{} [{}] --> {}'.format(self.get_now_time(), level.upper(), content)]
                try:
                    # 将日志传送错误加入日志中
                    #logtext.append(str(traceback.format_exc()))
                    logpath = os.path.dirname(LOG_FILE)
                    # 如果日志目录不存在，则创建目录
                    if not os.path.exists(logpath):
                        os.makedirs(logpath)
                    # 打开文件写日志
                    fp = open(LOG_FILE,'a',encoding='utf-8')
                    for line in logtext:
                        fp.write(line)
                        fp.write('\n')
                    fp.close()
                except:
                    pass


    def get_now_time(self):
        import time
        ct = time.time()
        local_time = time.localtime(ct)
        data_head = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
        data_secs = (ct - int(ct)) * 1000
        time_stamp = "%s.%03d" % (data_head, data_secs)
        return time_stamp

    def send(self, msg):
        '''发送日志到日志服务器，msg为一条日志'''
        self.writeLog(msg)

    def send_picture(self, file_path):
        '''
        发送图片到日志服务器，如果发送不成功则保存本地

        :Args:
         - filePath: 截图后图片所在的本地路径

        :Returns:
            返回图片保存的位置
        '''
        fp = open(file_path, "rb")
        del_flag = True
        try:
            url = self.url
            file_name = os.path.basename(file_path)
            data = dict()
            data['path'] = file_path
            data['mediaType'] = 'image/png'
            data = json.dumps(data).encode(encoding='utf-8')
            headers = {'Content-Type': 'application/json'}
            request = urllib.request.Request(url=self.url, headers=headers)
            response = urllib.request.urlopen(request, data)
            # 请求成功，则在日志中写入图片的路径
            body_content = json.loads(response.read().decode('utf-8'))
            print(body_content)
            if body_content.get('result').upper() == 'OK':
                rfp = body_content['msg']
            else:
                raise Exception('{}上传不成功！{}'.format(file_name, body_content.get('msg')))
        except Exception as e:
            logtext = '{} [{}] --> {}'.format(self.get_now_time(), 'Debug', e)
            self.writeLog(logtext)
            del_flag = False
            rfp = file_path
        finally:
            # 关闭图片
            fp.close()
            # 删除本地图片
            if del_flag:
                os.remove(file_path)
        return rfp
